/*
 * Copyright (c) 2025 Li Auto Inc. and its affiliates
 * Licensed under the Apache License, Version 2.0(the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <nuttx/config.h>
#include <nuttx/clock.h>
#include <nuttx/arch.h>
#include <sys/types.h>
#include "IfxStm.h"

#define STM0_FREQ (100000000UL)
#define TICKS_PER_US (STM0_FREQ / 1000000UL)

static inline_function uint64_t stm_timer_gettick(void)
{
	volatile const Ifx_STM *const stm = &MODULE_STM0; /* 使用 STM0 */
	volatile uint32_t upper = 0xFFFFFFFFU;
	volatile uint32_t lower = 0UL;

	do {
		upper = stm->TIM6.U;
		lower = stm->TIM0.U;
	} while (upper != (stm->TIM6.U));

	return (uint64_t)(((uint64_t)upper << 32) | (uint64_t)lower);
}

uint32_t up_timer_freq(void)
{
	return STM0_FREQ;
}

int up_timer_value(FAR clock_t *ticks)
{
	(*ticks) = stm_timer_gettick();
	return OK;
}

void up_udelay(uint32_t us)
{
	uint64_t start_time;
	uint64_t end_time;

	if (0u == us) {
		return;
	}

	start_time = stm_timer_gettick();
	end_time = start_time + ((uint64_t)us * TICKS_PER_US);
	while (stm_timer_gettick() < end_time) {
	}
}
